package com.qingfeng.client.service;

import com.qingfeng.client.bean.Buyer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis操作Service的实现类
 *
 */
@Service
public class RedisService{
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisTemplate redisTemplate;

    private int tokenExpire=1800;

    private String tokenPre = "jerryToken-";

    public void set(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    public boolean expire(String key, long expire) {
        return stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    public void remove(String key) {
        stringRedisTemplate.delete(key);
    }

    public Long increment(String key, long delta) {
        return stringRedisTemplate.opsForValue().increment(key,delta);
    }

    public void setObject(String key, Object object,long expire){
        redisTemplate.opsForValue().set(key,object,expire,TimeUnit.SECONDS);
    }

    public Object getObject(String key){
        return redisTemplate.opsForValue().get(key);
    }

    public void  expireObject(String key,long expire){
        redisTemplate.expire(key,expire,TimeUnit.SECONDS);
    }

    public void removeObject(String key){
        redisTemplate.delete(key);
    }


    public String setToken(Buyer buyer){
        String token = DigestUtils.md5DigestAsHex(buyer.getOpenId().getBytes());
        setObject(tokenPre+token,buyer,tokenExpire);
        return token;
    }

    public Buyer getToken(String token){
        return (Buyer) getObject(tokenPre+token);
    }

    public void updateTokenTime(String key){
        redisTemplate.expire(tokenPre+key,tokenExpire,TimeUnit.SECONDS);
    }

    /**
     * 获取当前在线token数量
     * @return
     */
    public int getTokenNum(){
       Set<String> sets = redisTemplate.keys(tokenExpire+"*");
       return sets.size();
    }

}
